from typing import List, Any
from dataclasses import dataclass, asdict,is_dataclass
import json

import tornado.ioloop
import tornado.web
from openai import OpenAI

client = OpenAI(api_key="你的API")

@dataclass
class StringVector:
    questions: List[str]
    model: str
    keyword: str

def ok_response(data: Any) -> str:
    # 1) 如果是 dataclass，就用 asdict
    if is_dataclass(data):
        payload = asdict(data)

    # 2) 如果是列表，且列表里每项都是 dataclass，也一并展开
    elif isinstance(data, list) and all(is_dataclass(item) for item in data):
        payload = [asdict(item) for item in data]

    # 3) 如果有 to_dict 方法（如 OpenAIObject），就调用它
    elif hasattr(data, "to_dict") and callable(data.to_dict):
        payload = data.to_dict()

    # 4) 其它一律原样返回（假定它已经是 dict、list、基本类型等可序列化的）
    else:
        payload = data

    # 使用 json.dumps 将对象转为 JSON 字符串
    return json.dumps({
        "data": payload,
        "code": 200,
        "message": None
    },ensure_ascii=False)

# 定义一个处理器类，继承自 tornado.web.RequestHandler
class test2vec_handler(tornado.web.RequestHandler):
    def post(self):
        body = self.request.body
        data = json.loads(body)
        # 将字典转换为 StringVector 数据类实例
        string_vector = StringVector(**data)

        response = client.embeddings.create(
            input= string_vector.questions,
            model="text-embedding-3-small"
        )

        embeddings = [item.embedding for item in response.data]
        print("已计算字符串"+",".join(string_vector.questions))
        self.set_header("Content-Type", "application/json")
        self.write(ok_response(embeddings))


# 定义应用程序类，指定路由
def make_app():
    return tornado.web.Application([
        (r"/text2vec", test2vec_handler),  # 将 "/" 路径映射到 MainHandler
    ])

# 启动服务器
if __name__ == "__main__":
    app = make_app()
    app.listen(8082)  # 监听 8888 端口
    tornado.ioloop.IOLoop.current().start()  # 启动事件循环